// index page
// ============

define([ 'require', 'zepto', 'wx', 'dropwizard', 'utils', 'sui'],
    function(require, $, wx, dropwizard, utils) {
      return {
        init : function(data) {
          this.initPage();
          this.initModal(data.pickupLocationId, data.returnLocationId)
          this.stayingOrder(data)
          this.payOrder(data);
          this.payNow();
          this.arrivePayNow();
        },
        
        initPage: function() {
          $('#drop').dropwizard()

          $('#drop').on('shown:fancy:dropwizard', function(e) {
            console.log(e)
          })
        },
        
        initModal: function(pickupLocationId, returnLocationId) {
            var that = this;
            $.ajax({
              type: "GET",
              url: window.__CTX__.root + "/locations/"+pickupLocationId+"/working-hours",
              dataType: "json",
              success: function(data) {
                if(data.code == 0) {
                   console.log("s",data.data)
                    var pickupWorkHtml = ""
                    $.each(data.data.workingHours, function(index, item){
                      pickupWorkHtml+= '<p style="margin: .25rem 0;"><span style="font-weight: bold;">'+ index +'</span>： ' + item + '</p>'
                    });
                    that.pickupWorkHtml = pickupWorkHtml
                } else {
                  $.toast(data.message);
                }
              },
              error: function() {
                $.toast("查询失败");
              }
            })
            
            $.ajax({
              type: "GET",
              url: window.__CTX__.root + "/locations/"+returnLocationId+"/working-hours",
              dataType: "json",
              success: function(data) {
                if(data.code == 0) {
                	console.log("d",data.data)
                    var returnLocationId = ""
                    $.each(data.data.workingHours, function(index, item){
                    	returnLocationId+= '<p style="margin: .25rem 0;"><span style="font-weight: bold;">'+ index +'</span>： ' + item + '</p>'
                    });
                    
                    that.returnLocationId = returnLocationId;
                } else {
                  $.toast(data.message);
                }
              },
              error: function() {
                $.toast("查询失败");
              }
            })
            
        	$(document).on('click','.icon-layout .iconfont', function (e) {
        	    $.modal({
                  title:  '营业时间',
                  text: '<div class="business-hours">'+
        	      ($(e.currentTarget).data("work") == "pickupLocation" ? that.pickupWorkHtml : that.returnLocationId)
          	            +'</div>',
                  buttons: [
                    {
                      text: '<span style="color: #5d5c5c;">关闭</span>',
                    },
                  ],
                  extraClass: 'business-hours-modal'
                })
        	  });
              
              $(document).on('click', '.modal-overlay', function() {
                $.closeModal('.modal');
              })
        },
        
        stayingOrder: function(data) {
          var that = this;
          $(".staying-button").on("click", function(e){
            var href= $(this).data("href");
            $.showPreloader('正在保留订单')
            $.ajax({
              type: "POST",
              url: window.__CTX__.root + "/shopping/orders/" + data.orderId + "/staying",
              dataType: "json",
              success: function(data) {
                $.hidePreloader();
                if(data.code == 0) {
                  var orderId = data.data.order.id;
                  
                  that.requestOrderStayingMessage(data.data.agent.mobile, orderId, function(data){},function(){});
                  setTimeout(function() {
                	  window.location.href = href;
                  }, 1000)
                } else {
                  $.toast(data.message);
                }
              },
              error: function() {
                $.toast("保留失败");
              }
            })
          })
        },
        
        isMobile: function(mobile) {
          return mobile && /^((13)|(16)|(15)|(17)|(18))\d{9}$/.test(mobile)
        },
        
        payOrder: function(e) {
          var that = this;
          $(".pay-button").on("click", function(e){
            e.preventDefault();
            var href= $(this).data("href");
            var $form = $("#orderForm");
            
            var $firstName = $("input[name='firstName']");
            var $lastName = $("input[name='lastName']");
            var $userPhone = $("input[name='userPhone']");
            var $userEmail = $("input[name='userEmail']");
            var $airportNumber = $("input[name='airportNumber']");
            
            if(!$firstName.val() || !$lastName.val() || !that.isPinyin($firstName.val()) || !that.isPinyin($lastName.val())) {
              $.toast("请输入正确的用户姓名拼音");
              return
            }
            
            if(!$userPhone.val() || !that.isMobile($userPhone.val())) {
              $.toast("请输入正确的用户手机");
              return
            }
            
            if(!$userEmail.val() || !that.isEmail($userEmail.val())) {
              $.toast("请输入正确的用户邮箱");
              return
            }
            
            if(!$airportNumber.val()) {
              $.toast("请输入正确的航班号");
              return
            }
            
            $.showPreloader('正在提交用户信息')
            
            // serialize parameters
            var parameters = $form.serializeArray()
            
            $.ajax({
              type: "POST",
              url: href,
              dataType: "json",
              data: parameters,
              success: function(data) {
                $.hidePreloader();
                if(data.code == 0) {
                  var orderId = data.data.order.id;
                  window.location.href = window.__CTX__.root + "/shopping/orders/" + orderId
                } else {
                  $.toast(data.message);
                }
              },
              error: function() {
                $.toast("创建失败");
              }
            })
          })
        },
        
        payNow: function() {
            var currentThat = this;
        	$('.pay-now').click(function(e) {
                e.preventDefault();
        		if($('input[name="agree"]').is(':checked')) {
                  var that = $(this);
                  that.attr('disabled', true);
                  $.showPreloader('正在提交订单');
        			var href = $(this).data("href");
            		var redirect = $(this).data("redirect")
            		$.ajax({
    	              type: "POST",
    	              url: href,
    	              dataType: "json",
    	              success: function(data) {
    	                $.hidePreloader();
    	                if(data.code == 0) {
//                        var orderId = data.data.order.id;
//    	                  currentThat.requestOrderMessage(data.data.agent.mobile, orderId, function(data){},function(){});
    	                  window.location.href = redirect
    	                } else {
    	                  $.toast(data.message);
    	                }
    	              },
    	              error: function() {
    	                that.attr('disabled', false);
    	                $.toast("创建失败");
    	              }
    	            })
        		} else {
        			$.toast("请同意条款！")
        		}
        		
	        })
        },
        
        arrivePayNow: function() {
            var currentThat = this;
        	$('.arrive-pay-now').click(function(e) {
                e.preventDefault();
        		if($('input[name="agree"]').is(':checked')) {
        		  var that = $(this);
                  that.attr('disabled', true);
                  $.showPreloader('正在提交订单')
        			var href = $(this).data("href");
            		var redirect = $(this).data("redirect")
            		$.ajax({
    	              type: "POST",
    	              url: href,
    	              dataType: "json",
    	              success: function(data) {
    	                $.hidePreloader();
    	                if(data.code == 0) {
    	                  var orderId = data.data.order.id;
    	                  currentThat.requestOrderMessage(data.data.agent.mobile, orderId, function(data){},function(){});
    	                  window.location.href = redirect
    	                } else {
    	                  $.toast(data.message);
    	                }
    	              },
    	              error: function() {
                        that.attr('disabled', false);
    	                $.toast("创建失败");
    	              }
    	            })
        		} else {
        			$.toast("请同意条款！")
        		}
        		
	        })
        },
        
        /**
         * Request server to send order staying message to mobile
         */
        requestOrderStayingMessage: function(mobile, orderId, success, failure) {
          $.showIndicator()
          utils.requestStayingOrderMessage(mobile, orderId, function(result) {
            $.hideIndicator()
            success && success(result.data)
          }, failure)
        },
        
        /**
         * Request server to send order cancel message to mobile
         */
        requestOrderMessage: function(mobile, orderId, success, failure) {
          $.showIndicator()
          utils.requestOrderMessage(mobile, orderId, function(result) {
            $.hideIndicator()
            success && success(result.data)
          }, failure)
        }
        
      }
    })